// pages/groupBuy/groupBuy.js


import utils from '../../utils/util.js';
import {
  PATHS_ALIAS, OTHER_INFO
} from '../../utils/api.js'

import {
  http
} from '../../utils/network.js'

// 倒计时计时器
let timer = '';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    checkLogin: '',      //登录信息是否齐全
    loginAgainStatus: false, //再次登录结果  true 成功    false 失败
    fromPage: '',      //登录成功回调的页面
    groupId: '', //团的id
    userId: '', //用户id
    activityId:'',      //活动Id
    ticketId:'',      //参团--活跃票种id
    groupInfo: '', //团的信息
    groupPlayerList:[],     //参团者列表
    hotList: [], //大家都在拼
    sysTime: '', //服务器时间--获取拼团详情时间
    sysTimeActDetail: '', //服务器时间--获取活动详情时间
    actDetail: '',
    ticketList: [],
    ticketShow: false, //票种列表展示
    goTopShow:false,      //回到顶部
    groupIsNone:false,     //拼团是否不存在
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // //console.log(options);
    // 拼团id
    let groupId = options.groupId;
    // let groupId = groupId=2658;
    let userId = wx.getStorageSync('userId');
    // 检查登录信息
    let checkLogin = this.selectComponent('#loginCheck').checkLogin();
    this.setData({
      groupId: groupId ? groupId : '',
      userId: userId ? userId : '',
      checkLogin
    });
  },
  onShow: function () {
    this.setData({
      userId: wx.getStorageSync('userId'),
      ticketShow:false
    });
    this.getGroupInfo();
  },
  onHide: function () {
    wx.hideLoading();
    clearInterval(timer);
  },
  // 获取滚动条当前位置
  onPageScroll: function (e) {
    // console.log(e)
    if (e.scrollTop > 300) {
      this.setData({
        goTopShow: true
      });
    } else {
      this.setData({
        goTopShow: false
      });
    }
  },
  // 获取热门拼团
  getHotList: function (activityId){
    let _this = this;
    let params = {
      activityId: activityId,      //	活动ID	string	
      page:1,       //	页数	string	
      pageSize:10,      //	每页大小	string	
    };
    http({
      path: PATHS_ALIAS.GET_GROUP_LIST,
      params:params,
      success:function(res){
        let groupActList = res.response.groupActList;
        groupActList.forEach(function (item, i) {
          groupActList[i].minGroupBuyPrice = item.groupBuyPrice.split('-')[0];
          groupActList[i].MinEntryFee = item.entryFee.split('-')[0];
        });
        _this.setData({
          hotList: groupActList
        });
      },
      fail:function(err){
        //console.log(err)
      }
    })
  },
  // 获取拼团信息
  getGroupInfo: function() {
    let _this = this;
    let params = {
      groupId: this.data.groupId, //	拼团订单的团ID	number	必填
      realUserId: this.data.userId, //	统一用户userId	string	必填
    };
    http({
      path: PATHS_ALIAS.GET_GROUP_DETAIL,
      params: params,
      success: function(res) {
        //console.log(res);
        let groupInfo = res.response;
        // 最低活动价格
        groupInfo.entryFeeMin = groupInfo.entryFee.split('-')[0];
        // 最低拼团价格
        groupInfo.groupBuyPriceMin = groupInfo.groupBuyPrice.split('-')[0];
        // 拼团剩余时间戳
        groupInfo.leftTimestamp = utils.timeToTimestamp(groupInfo.tradeTime) + groupInfo.groupBuyDeadLine * 60 * 60 * 1000 - utils.timeToTimestamp(res.systemDate);
        // 活动图片
        groupInfo.actPic = groupInfo.rfdsUrl + groupInfo.activityPicList.split(',')[0];
         //剩余拼团人数
        groupInfo.surplus = groupInfo.groupBuyNum - groupInfo.groupInfo.length;
        // 整理已报名人员列表
        let groupPlayerList = groupInfo.groupInfo;
        for (let i = 0; i < groupInfo.surplus; i++) {
          if (groupInfo.groupOrderStatus == 'group_success'){     //如果是拼团成功状态，但是团成员不足时，用虚拟头像补全
            let groupItem = {
              headImgUrl:'',
              entryStatus:'refund'
            };
            groupPlayerList.push(groupItem);
          }else{
            groupPlayerList.push('');
          }
        };
        _this.getHotList(groupInfo.activityId);
        _this.setData({
          sysTime: res.systemDate,
          groupInfo,
          groupPlayerList,
          activityId: groupInfo.activityId
        });
        if (groupInfo.groupOrderStatus == 'grouping'){   //拼团中--倒计时
          clearInterval(timer);   //先清除计时器
          _this.leftTimeRun();
        }
      },
      fail: function(err) {
        //console.log(err);
        if(err.code == '-1'){     //
          setTimeout(function(){
            wx.navigateBack({
              delta: 1
            });
          },500);
        } else if (err.code == '-7001'){    //该拼团不存在
          _this.setData({
            groupIsNone:true
          });
          wx.showModal({
            title: '',
            content: '该团不存在，看看别的活动？',
            showCancel: false,
            confirmColor: '#F45450',
            success: function (res) {
              wx.switchTab({
                url: '/pages/index/index',
              })
            }
          })
        }
      }
    })
  },
  // 重新开团
  beginGroup:function(e){
    //console.log(e);
    // //console.log(e);
    let checkLogin = this.data.checkLogin;
    if (!checkLogin) {
      this.setData({
        // afterLoginEvent: 'beginGroup',
      })
    } else {
      let activityid = this.data.activityId;
      wx.navigateTo({
        url: `/pages/actDetail/actDetail?id=${activityid}`,
      })
    }
  },
  // 参团-确定
  goGroup: function (e) {
    // //console.log(e);
    let ticketId = e.currentTarget.dataset.ticketid;
    let activityId = this.data.activityId;
    let groupId = this.data.groupId;
    let checkLogin = this.data.checkLogin;
    if (!checkLogin) {
      this.setData({
        // afterLoginEvent: 'goGroup',
        ticketId
      })
    } else {
      wx.navigateTo({
        url: `/pages/submitOrder/submitOrder?ticketId=${ticketId}&activityId=${activityId}&groupId=${groupId}`
      })
    }
  },
  // 票种列表弹框显示
  ticketShow: function() {
    this.getActDetail();
    this.setData({
      ticketShow: true
    })
  },
  // 票种列表弹框隐藏
  ticketHide: function() {
    this.setData({
      ticketShow: false
    })
  },
  // 获取活动详情
  getActDetail: function() {
    let _this = this;
    let params = {
      activityId: this.data.activityId
    };
    http({
      path: PATHS_ALIAS.GET_GROUP_ACT_DETAIL,
      params: params,
      success: function(res) {
        // //console.log(res)
        let ticketList = res.response.groupActTicket;
        _this.setData({
          sysTimeActDetail: res.systemDate,
          actDetail: res.response.groupActDetail,
          ticketList,
        });
        _this.filterTicketTime(ticketList);
      },
      fail(err) {
        wx.showToast({
          title: err.msg,
          icon: 'none'
        });
        setTimeout(function() {
          wx.navigateBack({
            delta: 1
          })
        }, 1500)
      }
    });
  },
  // 计算票种报名时间及状态
  filterTicketTime(arr) {
    let _this = this;
    let ticketList = arr;
    let actDetail = this.data.actDetail;
    ticketList.forEach(function(item, index) {
      if (item.entryNumFull == 'N' && item.entryStatus == 'N' && actDetail.ticketCalendar == 'Y') { //有日历，计算最早报名时间
        let nearestBookDay = item.nearestBookTime.slice(0, 10);
        if (nearestBookDay) {
          let today, nearDay, timeInterval;
          today = utils.formatTime(new Date()).slice(0, 10);
          nearDay = nearestBookDay.replace(/-/g, '/');
          timeInterval = new Date(nearDay) - new Date(today);
          if (timeInterval == 0) {
            ticketList[index].ticketStatusTxt = '最早可预订今天';
          } else if (timeInterval == 24 * 60 * 60 * 1000) {
            ticketList[index].ticketStatusTxt = '最早可预订明天';
          } else {
            nearDay = new Date(nearDay);
            ticketList[index].ticketStatusTxt = "最早可订" + (nearDay.getMonth() + 1) + "月" + nearDay.getDate() + "日";
          }
        };
        ticketList[index].ticketStatus = 'filterTime' //票种状态  filterTime（最早报名时间） full（名额已满） end(报名结束) before(拼团未开始)
      } else if (item.entryNumFull == 'Y') { //票种名额已满
        ticketList[index].ticketStatus = 'full'
        ticketList[index].ticketStatusTxt = ''
      } else if (item.entryNumFull == 'N' && item.entryStatus == 'group_before'){     //票种拼团报名未开始
        ticketList[index].ticketStatus = 'before'
        ticketList[index].ticketStatusTxt = ''
      } else if (item.entryNumFull == 'N' && item.entryStatus == 'end') { //票种报名时间已结束
        ticketList[index].ticketStatus = 'end'
        ticketList[index].ticketStatusTxt = ''
      } else {} //没有票种日历不展示   
    });
    this.setData({
      ticketList
    })
  },
  // 参团倒计时
  leftTimeRun: function() {
    let _this = this;
    _this.leftTimeRunFilter();
    timer = setInterval(function() {
      let leftTimestamp = _this.leftTimeRunFilter();
      if (leftTimestamp < 0) {
        clearInterval(timer);
        _this.getGroupInfo();
      }
    }, 1000)
  },
  // 参团倒计时--计算时间
  leftTimeRunFilter: function() {
    let groupInfo = this.data.groupInfo;
    groupInfo.leftTimestamp = groupInfo.leftTimestamp - 1000;
    this.setData({
      groupInfo
    });
    return groupInfo.leftTimestamp;
  },
  // 再次登录--及回调控制  type: beginGroup开团  goGroup参团
  loginThird: utils.throttle(function (e) {
    //console.log(e);
    let _this = this;
    let type = e.currentTarget.dataset.type;
    let fromPage = '';
    let checkLogin = this.data.checkLogin; //登录信息是否存在
    let activityId = this.data.activityId;
    let ticketId = e.currentTarget.dataset.ticketid;
    let groupId = this.data.groupId;
    switch (type) {
      case 'beginGroup':
        fromPage = `/pages/actDetail/actDetail?id=${activityId}`
        break;
      case 'goGroup':
        fromPage = `/pages/submitOrder/submitOrder?ticketId=${ticketId}&activityId=${activityId}&groupId=${groupId}`
        break;
    };
    this.setData({
      fromPage: encodeURIComponent(fromPage)
    });
    if (checkLogin) { //重新登录
      wx.showLoading({
        title: '加载中...',
        mask: true
      });
      let params = {
        logType: '07',
        thirdId: wx.getStorageSync('unionId'),
        resId: 'weixin',
        userSystem: '0052'
      };
      http({
        path: PATHS_ALIAS.THIRD_USER_LOGIN,
        params: params,
        header: {
          sendChl: 'hzsmk.h5', // 应用渠道(必填) 
          sendClient: 'hellohzsmk', //应用验证码(必填) string 
          clientCode: OTHER_INFO.clientCode
        },
        success: function (res) {
          //console.log(res);
          wx.setStorageSync('accessToken', res.response.accessToken);
          wx.setStorageSync('userId', res.response.userId);
          wx.setStorageSync('mobile', res.response.mobile);
          _this.setData({
            loginAgainStatus: true,
            checkLogin: true
          });
          switch (type) {
            case 'beginGroup':
              _this.beginGroup(e);
              break;
            case 'goGroup':
              _this.goGroup(e);
              break;
          }
        },
        fail: function (err) {
          //console.log(err);
          _this.setData({
            loginAgainStatus: false
          });
          if (err.code == 'PY0005') { //跳转输入手机号登录
            wx.navigateTo({
              url: `/pages/phoneLogin/phoneLogin?fromPage=${_this.data.fromPage}`,
            })
          }
        },
        complete: function () {

        }
      })
    } else {
      this.selectComponent('#loginCheck').loginAgain();
    }
  },3000),
  //回到顶部
  goTop: function (e) {  // 一键回到顶部
    wx.pageScrollTo({
      scrollTop: 0
    })
  },
  // 登录成功回调
  loginSuccess: function (e) {
    // //console.log(e);
    if (e.detail.status == '0') {
      this.setData({
        checkLogin: true
      });
      this.onShow();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

 

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享 数据模型
   */
  onShareAppMessage: function(res) {
    var _this = this;
    let groupInfo = this.data.groupInfo;
    let title = '';
    
    if (groupInfo.groupOrderStatus == 'grouping' && groupInfo.surplus != 0){  //拼团中 -- 且剩余名额大于0
      if (groupInfo.userEntry == 'Y') {    // 团内成员
        title = `【仅剩${groupInfo.surplus}个名额】我${groupInfo.ticketPrice / 10 / 10}元拼了 ${groupInfo.theme}`;
      } else {    //非团内成员
        title = `【仅剩${groupInfo.surplus}个名额】${groupInfo.groupBuyPriceMin}元拼 ${groupInfo.theme}`;
      };
    }else{      //拼团失败或拼团成功
      title = `${groupInfo.theme}`;
    };
    
    let path = `/pages/groupBuy/groupBuy?groupId=${_this.data.groupId}`;
    //console.log(res)
    // res.from可以用来判断是从自定义button打开的转发页面，还是从右上角的打开的转发页面。
    if (res.from == 'button') { //按钮1 触发的分享
      // 自定义转发内容  return 一个Object
      return {
        title: title,
        path: path,
        // imageUrl: 'https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKuicssx7Pib0QVDIzXCbF2IxAInNZsFNEOtJVdtPJmTlwqD0lR9wnLjpfgLxGLoqud2wBCJdwngy3Q/132',
        // 转发成功的回调函数 第一次上报
        success: function(res) {
          //console.log('转发成功了，第一次上报：' + res);
        },
        fail: function(res) {}
      }
    } else if (res.from == 'menu') { //系统按钮触发的分享
      // 自定义转发内容  return 一个Object
      return {
        title: title,
        path: path,
        // imageUrl: 'http://e.hiphotos.baidu.com/zhidao/pic/item/58ee3d6d55fbb2fb070c9ca94e4a20a44623dc62.jpg'
      }
    }
  },
})